package com.ch.mobilesha.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.ch.mobilesha.base.BaseBean;
import com.ch.mobilesha.net.MyHttpAPI;

public class UtilTools {

	/**
	 * 获取int类型的sp值
	 * 
	 * @param context
	 * @param sp
	 * @param key
	 * @param value
	 */
	public static int getIntSharedPreferences(Context context, String sp, String key, int defValue) {
		SharedPreferences sps = context.getSharedPreferences(sp, Context.MODE_PRIVATE);
		return sps.getInt(key, defValue);
	}

	/**
	 * 设置int类型的sp值
	 * 
	 * @param context
	 * @param sp
	 * @param key
	 * @param value
	 */
	public static void setIntSharedPreferences(Context context, String sp, String key, int value) {
		SharedPreferences sps = context.getSharedPreferences(sp, Context.MODE_PRIVATE);
		Editor editor = sps.edit();
		editor.putInt(key, value);
		editor.commit();
	}

	/**
	 * 获取int类型的sp值
	 * 
	 * @param context
	 * @param sp
	 * @param key
	 * @param value
	 */
	public static String getStringSharedPreferences(Context context, String sp, String key, String defValue) {
		SharedPreferences sps = context.getSharedPreferences(sp, Context.MODE_PRIVATE);
		return sps.getString(key, defValue);
	}

	/**
	 * 设置String类型的sp值
	 * 
	 * @param context
	 * @param sp
	 * @param key
	 * @param value
	 */
	public static void setStringSharedPreferences(Context context, String sp, String key, String value) {
		SharedPreferences sps = context.getSharedPreferences(sp, Context.MODE_PRIVATE);
		Editor editor = sps.edit();
		editor.putString(key, value);
		editor.commit();
	}

	/**
	 * 清空sp
	 * 
	 * @param context
	 * @param sp
	 * @param key
	 * @param value
	 */
	public static void clearSharedPreferences(Context context, String sp) {
		SharedPreferences sps = context.getSharedPreferences(sp, Context.MODE_PRIVATE);
		Editor editor = sps.edit();
		editor.clear();
		editor.commit();
	}

	/**
	 * 判断非空及""字符
	 * 
	 * @param src
	 * @return
	 */
	public static boolean isNotNullOrEmpty(String src) {
		if (src == null) {
			return false;
		} else if (src.trim().equals("")) {
			return false;
		} else if (src.equals("null")) {
			return false;
		}
		return true;
	}

	/**
	 * 安装应用
	 * 
	 * @param context
	 * @param installName
	 */
	public static void setupApk(Context context, String installName, String fromFile) {
		String fileName = "";
		if (fromFile != null) {
			fileName = fromFile;
		} else {
			fileName = context.getApplicationContext().getFilesDir() + "/" + installName;
		}
		System.out.println(fileName);
		Uri uri = Uri.fromFile(new File(fileName));
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		context.startActivity(intent);
	}

	/**
	 * 判断是否安装过某程序
	 * 
	 * @param context
	 * @param packageName
	 * @return
	 */
	public static boolean isInstall(Context context, String packageName, boolean isEquals) {
		PackageManager pckMan;
		pckMan = context.getPackageManager();
		List<PackageInfo> packs = pckMan.getInstalledPackages(0);
		for (int i = 0; i < packs.size(); i++) {
			PackageInfo p = packs.get(i);
			if (isEquals && packageName.equals(p.packageName)) {
				return true;
			} else if (!isEquals && p.packageName.contains(packageName)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取下载的handler
	 * 
	 * @param context
	 * @param installFileName
	 * @param progressDialog
	 * @return
	 */
	public static Handler getDownLoadHandler(final Context context, final String installFileName, final ProgressDialog progressDialog) {
		Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 0:
					int result = msg.getData().getInt("len");
					progressDialog.setProgress(result);
					break;

				case 1:
					File file = new File(context.getFilesDir() + "/" + installFileName);
					if (file.exists())
						file.delete();
					progressDialog.dismiss();
					break;

				case 2:
					if (progressDialog.getProgress() < 100) {
						progressDialog.setProgress(0);
						for (int i = 1; i < 51; i++) {
							progressDialog.setProgress(i * 2);
							try {
								Thread.sleep(20);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
					setupApk(context, installFileName, null);
					progressDialog.dismiss();
					break;

				case 3:
					Toast.makeText(context.getApplicationContext(), "抱歉，下载失败， 请稍后再试", Toast.LENGTH_SHORT).show();
					progressDialog.dismiss();
					break;
				}
			}
		};
		return handler;
	}

	public static boolean isStop = false;
	public static final int DOWNLOADING = 0;
	public static final int DOWNLOADINTERRUPT = 1;
	public static final int DOWNLOADOVER = 2;
	public static final int DOWNLOADERROR = 3;

	public static void downLoadWithHandlerFromUrl(Context context, String url, String fileName, Handler handler) {
		DefaultHttpClient httpClient = new MyHttpAPI().getDefaultHttpClient();
		HttpGet request = new HttpGet(url);
		Message message = null;
		try {
			URL urlCon = new URL(url);
			HttpResponse response = httpClient.execute(request);
			HttpEntity entity = response.getEntity();
			InputStream inputStream = urlCon.openStream();
			int filesize = (int) entity.getContentLength();
			if (filesize > 0) {
				FileOutputStream os = context.openFileOutput(fileName, Context.MODE_WORLD_READABLE);
				int len = 0;
				int downloadfilesize = 0;
				byte[] data = new byte[1024];
				while ((len = inputStream.read(data)) != -1) {
					if (!isStop) {
						os.write(data, 0, len);
						downloadfilesize += len;
						message = new Message();
						message.what = DOWNLOADING;
						Bundle bundle = new Bundle();
						bundle.putInt("len", downloadfilesize * 100 / filesize);
						message.setData(bundle);
						handler.sendMessage(message);
					} else {
						os.close();
						message = new Message();
						message.what = DOWNLOADINTERRUPT;
						handler.sendMessage(message);
						return;
					}
				}
				os.close();
			}
			message = new Message();
			message.what = DOWNLOADOVER;
			handler.sendMessage(message);
		} catch (Exception e) {
			e.printStackTrace();
			message = new Message();
			message.what = DOWNLOADERROR;
			handler.sendMessage(message);
		}
	}

	public static ProgressDialog getDownProgress(Context context, String title, String message, OnCancelListener onCancelListener) {
		ProgressDialog progressDialog = new ProgressDialog(context);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setTitle(title);
		progressDialog.setMessage(message);
		progressDialog.setIndeterminate(false);
		progressDialog.setCancelable(true);
		progressDialog.setOnCancelListener(onCancelListener);
		progressDialog.setMax(100);
		return progressDialog;
	}

	public static boolean isServiceStart(Context context, String className) {
		boolean result = false;
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningServiceInfo> services = am.getRunningServices(100);
		for (RunningServiceInfo rs : services) {
			if (rs.service.getClassName().equals(className)) {
				result = true;
			}
		}
		return result;
	}

	public static byte[] intToByte(int i) {
		byte[] bt = new byte[4];
		bt[0] = (byte) (0xff & i);
		bt[1] = (byte) ((0xff00 & i) >> 8);
		bt[2] = (byte) ((0xff0000 & i) >> 16);
		bt[3] = (byte) ((0xff000000 & i) >> 24);
		return bt;
	}

	public static <T> void getFieldFromJson(JSONObject jsonObject, T bean, Class<?> cl) {
		try {
			Field[] fields = cl.getDeclaredFields();
			@SuppressWarnings("unchecked")
			Iterator<String> it = jsonObject.keys();
			List<String> keys = new ArrayList<String>();
			while (it.hasNext()) {
				keys.add(it.next());
			}
			for (int i = 0; i < fields.length; i++) {
				if (!fields[i].getName().equals("jsonObject") && keys.contains(fields[i].getName())) {
					fields[i].setAccessible(true);
					if (fields[i].getType().equals(String.class)) {
						fields[i].set(bean, jsonObject.get(fields[i].getName()));
					} else {
						fields[i].set(bean, jsonObject.getInt(fields[i].getName()));
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> List<BaseBean> getListFromJSONArray(JSONArray ja, T bean, Class<?> cl) {
		try {
			List<BaseBean> result = new ArrayList<BaseBean>();
			for (int i = 0; i < ja.length(); i++) {
				bean = (T) Class.forName(cl.getName()).newInstance();
				getFieldFromJson(ja.getJSONObject(i), bean, cl);
				result.add((BaseBean) bean);
			}
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String copyFromAm(Context context, String fromFileName) {
		try {
			AssetManager am = context.getAssets();
			byte[] data = new byte[1024];
			int buffer;
			File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "sxtv");
			if (!dir.isDirectory()) {
				dir.mkdir();
			}
			String toFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "sxtv" + File.separator + fromFileName;
			FileOutputStream os = new FileOutputStream(new File(toFileName));
			int size = 0;
			InputStream is = am.open(fromFileName);
			while ((buffer = is.read(data)) != -1) {
				size = size + buffer;
				os.write(data, 0, buffer);
			}
			os.flush();
			os.close();
			return toFileName;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String formatLongToTimeStr(int l, String format) {
		int hour = 0;
		int minute = 0;
		int second = 0;

		second = l / 1000;
		if (second > 60) {
			minute = second / 60;
			second = second % 60;
		}
		if (minute > 60) {
			hour = minute / 60;
			minute = minute % 60;
		}
		String strHour = "";
		String strMinute = "";
		String strSecond = "";
		if (hour < 10) {
			strHour = "0";
		}
		if (minute < 10) {
			strMinute = "0";
		}
		if (second < 10) {
			strSecond = "0";
		}
		String str = "";
		if (hour != 0) {
			str = format.replace("HH", strHour + hour).replace("mm", strMinute + minute).replace("ss", strSecond + second);
		} else if (minute != 0) {
			str = format.replace("HH", "").replace("mm", strMinute + minute).replace("ss", strSecond + second);
		} else {
			str = format.replace("HH", "").replace("mm", "00").replace("ss", strSecond + second);
		}
		if (str.startsWith(":")) {
			str = str.substring(1);
		}
		return str;
	}

	public static String getCPUInfo() {
		String result = null;
		try {
			String[] args = { "/system/bin/cat", "/proc/cpuinfo" };
			result = run(args, "/system/bin/");
			Log.i("result", "result=" + result);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return result;
	}

	public synchronized static String run(String[] cmd, String workdirectory) throws IOException {
		String result = "";
		try {
			ProcessBuilder builder = new ProcessBuilder(cmd);
			// 设置一个路径
			if (workdirectory != null)
				builder.directory(new File(workdirectory));
			builder.redirectErrorStream(true);
			Process process = builder.start();
			InputStream in = process.getInputStream();
			byte[] re = new byte[1024];
			while (in.read(re) != -1) {
				result = result + new String(re);
			}
			in.close();

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}
}
